package com.mo.tools.verification.valid;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.net.MalformedURLException;

/**
 * @name: URLValidator
 * @description:
 * @author: Yang Xingfu
 * @date: 2021-01-29 15:55
 **/
public class URLValidator implements ConstraintValidator<URL, String> {
    private String protocol;
    private String host;
    private int port;

    public URLValidator() {
    }

    @Override
    public void initialize(URL url) {
        this.protocol = url.protocol();
        this.host = url.host();
        this.port = url.port();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        if (value != null && value.length() != 0) {
            java.net.URL url;
            try {
                url = new java.net.URL(value.toString());
            } catch (MalformedURLException var5) {
                return false;
            }

            if (this.protocol != null && this.protocol.length() > 0 && !url.getProtocol().equals(this.protocol)) {
                return false;
            } else if (this.host != null && this.host.length() > 0 && !url.getHost().equals(this.host)) {
                return false;
            } else {
                return this.port == -1 || url.getPort() == this.port;
            }
        } else {
            return true;
        }
    }
}

